import math
import sys
import time

from selenium.webdriver.common.by import By

from libs import config
from libs.action import WebDriverAction
from libs.game import Game
from libs.image import ImageTool
from libs.log import Log
from libs.movement import Movement, KeyCode
from libs.task_helper import TaskHelper
from libs.trade_helper import TradeHelper
from libs.window import AdsWindow


def goto_bus_station():
    plot_image = 'plot.png'
    target_loc = image_tool.find_target(plot_image)
    if target_loc is None:
        terra_center_image = 'terra_center.png'
        action.goto_terra()
        terra_loc = image_tool.find_target(terra_center_image)
        if terra_loc is None:
            action.goto_spec()
            action.goto_terra()
            terra_loc = image_tool.find_target(terra_center_image)
        terra_x, terra_y = terra_loc
        if terra_y < 420:
            movement.keep_move_up(0.5)

        not_move = False
        for loop in range(100):
            plot_loc = image_tool.find_target(plot_image)
            if plot_loc is not None:
                print('found plot')
                movement.send_key_up(KeyCode.LEFT)
                break
            movement.send_key_down(KeyCode.LEFT)
            time.sleep(0.1)
            new_terra_loc = image_tool.find_target(terra_center_image)
            if new_terra_loc is not None and terra_loc == new_terra_loc:
                if not_move:
                    not_move = False
                    movement.send_key_up(KeyCode.RIGHT)
                    movement.keep_move_right(0.1)
                    movement.keep_move_down(0.2)
                    movement.send_key_down(KeyCode.RIGHT)
                else:
                    not_move = True
            terra_loc = new_terra_loc

    action.move_to(plot_image, delta_x=40, delta_y=170, max_loop=2)
    time.sleep(1)
    return image_tool.find_target(plot_image)


if __name__ == "__main__":
    parser = TaskHelper.default_args_parser('Wine')
    args = parser.parse_args()
    task_helper = TaskHelper.from_args(args)

    user_id = args.user_id
    log = Log(user_id)
    driver = AdsWindow(user_id).open(False)
    game = Game(driver, user_id)
    action = WebDriverAction(driver)
    movement = Movement(driver)
    image_tool = ImageTool(driver)
    trade_helper = TradeHelper(driver, user_id)

    try:
        game.enter_game()
        game.get_backpack()
        seed_name = 'YGGourd Seeds'
        fruit_name = 'YGGourd'
        seed_qty = game.get_backpack_qty(seed_name)
        fruit_qty = game.get_backpack_qty(fruit_name)
        log.info(f'{seed_name}={seed_qty}')
        if seed_qty + fruit_qty >= 50:
            task_helper.add_task('ygg.py', delay_seconds=24 * 60 * 60, ignore_running=True, priority=9)
            task_helper.add_task('ygg_plant.py', delay_seconds=1 * 60, ignore_running=True, priority=8)
            task_helper.task_success()
            sys.exit()

        bs_loc = goto_bus_station()
        bs_x, bs_y = bs_loc
        action.click_by_offset(bs_x + 40, bs_y + 170)
        action.wait_page_loaded()
        movement.send_key_down(KeyCode.LEFT)
        for _ in range(20):
            door_loc = image_tool.find_target('ygg_door.png')
            if door_loc is None:
                continue
            else:
                time.sleep(1.3)
                movement.send_key_up(KeyCode.LEFT)
                action.move_to('ygg_door.png', delta_x=50, delta_y=100)
        movement.send_key_up(KeyCode.LEFT)
        action.wait_page_loaded()
        time.sleep(10)
        action.handle_dialog()
        action.handle_dialog()
        movement.keep_move_up(2)
        movement.keep_move_up(2)
        movement.keep_move_up(2)
        movement.keep_move_left(2)
        movement.keep_move_left(2)
        movement.keep_move_left(2)
        actions = [
            ('up', 0, 'click'),
            ('up', 2, 'click'),
            ('up', 2, 'click'),
            ('up', 2, 'click'),
            ('up', 1.2, 'click'),
            ('left', 4.5, ''),
            ('down', 1, ''),
            ('right', 1, 'click'),
            ('down', 2, 'click'),
            ('down', 2, 'click'),
            ('down', 2, 'click'),
            ('down', 2, 'click'),
            ('down', 2, ''),
            ('down', 2, ''),
            ('down', 2, ''),
            ('right', 6.5, ''),
            ('up', 3, ''),
            ('up', 3, ''),
            ('right', 3, ''),
            ('right', 3, 'click'),
            ('up', 2, 'click'),
            ('up', 2, 'click'),
            ('up', 2, 'click'),
            ('up', 1.5, 'click'),
            ('right', 4.5, ''),
            ('down', 1, ''),
            ('left', 1, 'click'),
            ('down', 2, 'click'),
            ('down', 2, 'click'),
            ('down', 2, 'click'),
            ('down', 2, 'click'),
            ('down', 2, 'click'),
        ]
        for (direction, move_seconds, do) in actions:
            if move_seconds > 0:
                if direction == 'up':
                    movement.keep_move_up(move_seconds)
                if direction == 'left':
                    movement.keep_move_left(move_seconds)
                if direction == 'down':
                    movement.keep_move_down(move_seconds)
                if direction == 'right':
                    movement.keep_move_right(move_seconds)
            if do == 'click':
                time.sleep(0.5)
                stool_locs = image_tool.find_all_targets('ygg_stool.png')
                for stool_loc in stool_locs:
                    action.click_by_offset(*stool_loc)

        game.get_backpack()
        seed_qty = game.get_backpack_qty(seed_name)
        if seed_qty >= 50:
            task_helper.add_task('ygg.py', delay_seconds=24 * 60 * 60, ignore_running=True, priority=9)
        else:
            task_helper.add_task('ygg.py', delay_seconds=10, retry=True, ignore_running=True, priority=9)
        if seed_qty > 0:
            task_helper.add_task('ygg_plant.py', delay_seconds=1 * 60, ignore_running=True, priority=8)

        task_helper.task_success()

    except Exception as e:
        task_helper.task_fail()
        task_helper.add_task('ygg.py', delay_seconds=1 * 60, ignore_running=True, priority=9, retry=True)
        raise e
